package cn.wgx.module.mind.websocket.util;

import cn.wgx.common.util.SpringContextHolder;
import cn.wgx.common.util.StringUtils;
import cn.wgx.module.mind.websocket.entity.BaseMessage;
import cn.wgx.module.mind.websocket.entity.MessageType;
import cn.wgx.module.mind.websocket.entity.WSPrincipal;
import cn.wgx.module.mind.websocket.web.WSController;
import org.springframework.messaging.simp.SimpMessagingTemplate;

import java.security.Principal;

public class RoomMsgSender {

    private static SimpMessagingTemplate simpMessagingTemplate = SpringContextHolder.getBean(SimpMessagingTemplate.class);

    public static void sendPublicMsg(String roomId, BaseMessage msg){
        simpMessagingTemplate.convertAndSend(WSController.url_sub_public_room.replace("{room}", roomId), msg.toJSONOString());
    }


    public static void sendPrivateMsgToUser(String roomId, String userId,  BaseMessage msg){
        simpMessagingTemplate.convertAndSendToUser(userId, WSController.url_sub_person_room.replace("{room}", roomId), msg.toJSONOString());
    }


    //各种包装消息重载
    public static BaseMessage wrap(String content, Principal wsPrincipal, MessageType type){
        return wrap(content, wsPrincipal, null, null, type);
    }

    public static BaseMessage wrap(String content, Principal wsPrincipal){
        return wrap(content, wsPrincipal, null, null, null);
    }


    public static BaseMessage wrap(String content, Principal wsPrincipal, String roomId, String toUser){
        return wrap(content, wsPrincipal, roomId, toUser, null);
    }

    /**
     * 过滤消息
     * @param content 消息正文
     * @param wsPrincipal 发送消息人
     * @param roomId 房间号
     * @param toUser 接受消息人
     * @param type 消息类型
     * @return
     */
    public static BaseMessage wrap(String content, Principal wsPrincipal, String roomId, String toUser, MessageType type){
        BaseMessage js = new BaseMessage();
        if(StringUtils.isBlank(content)){
            js.setContent("");
        }else if(content.length() > 100){
            content = content.substring(0,99);
        }
        js.setContent(content);
        if(type != null){
            js.setMsgType(type);
        }else{
            js.setMsgType(MessageType.TEXT);
        }
        js.setRoomId(roomId);
        js.setToUser(toUser);
        return wrap(js, wsPrincipal);
    }

    public static BaseMessage wrap(BaseMessage baseMessage, Principal wsPrincipal){
        if(wsPrincipal instanceof WSPrincipal){
            baseMessage.setFromUser((WSPrincipal)wsPrincipal);
        }
        String toUser = baseMessage.getToUser();
        if(StringUtils.isNotBlank(toUser) && StringUtils.isNotBlank(baseMessage.getRoomId())){
            WSPrincipal principal = OnlineUserTool.getPrincipal(baseMessage.getRoomId(), toUser);
            if(principal != null){
                baseMessage.setToUser(principal.getNickname());
            }
        }
        return baseMessage;
    }
}
